﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Diagnostics;
using System.Net;
using System.IO;
using System.Drawing.Imaging;
using Lyh.Train.Recognizer.UUWise;
using Lyh.Train.Data;

namespace Lyh.Train.Common.Http
{
    public class RandCodeHelper
    {
        public static Image GetRandCodeImage(string url)
        {
            Image image = null;
            bool flag = true;
            do
            {
                try
                {
                    HttpClient httpClient = new HttpClient(Context.Cookies);
                    if (Context.Proxy != "")
                    {
                        httpClient.Proxy = new WebProxy(Context.Proxy);
                    }
                    Stream imageStream = httpClient.GetImageStream(url, "", "", "", "", "get");
                    if (imageStream != null)
                    {
                        image = Image.FromStream(imageStream);
                        break;
                    }
                }
                catch
                {
                    break;
                }
            } while (flag);
            return image;
        }

        public static int GetRandCodeString(Image img, int codeType, ref StringBuilder res)
        {
            try
            {
                var ms = new MemoryStream();
                img.Save(ms, ImageFormat.Jpeg);
                var buffer = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
                ms.Flush();
                var codeId = UUWrapper.uu_recognizeByCodeTypeAndBytes(buffer, buffer.Length, codeType, res);
                ms.Close();
                ms.Dispose();
                return codeId;
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public static bool CheckRandCode(string code, string token)
        {
            HttpClient httpClient = new HttpClient(Context.Cookies);
            if (Context.Proxy != "")
            {
                httpClient.Proxy = new WebProxy(Context.Proxy);
            }
            string text = "randCode=" + code;
            if (token != "")
            {
                text = text + "&rand=randp&REPEAT_SUBMIT_TOKEN=" + token;
            }
            else
            {
                text += "&rand=sjrand";
            }
            string str = httpClient.Post(Context.CheckRandCodeUrl, text, Context.Host, Context.Origin, Context.LoginReferer, Context.HttpMethodPost);
            return HtmlHelper.GetContent(str, "\"data\":", ",").Replace("\"", "") == "Y";
        }
    }
}